package com.xii.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xii.pojo.Permission;
import com.xii.pojo.Role;
import com.xii.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 登录权限服务类
 */
@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findUserByUsername(username);
        if(user==null){
            return null;
        }
        //创建当前用户的权限集合
        List<GrantedAuthority> list = new ArrayList<>();
        //得到当前用户的角色集合
        Set<Role> roles = user.getRoles();
        for(Role role:roles){
            //集合添加当前角色的keyword
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            //通过角色获取到角色的权限的keyword
            Set<Permission> permissions = role.getPermissions();
            for(Permission permission:permissions){
                //每个权限的keyword添加到list
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        org.springframework.security.core.userdetails.User loginUser = new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
        return loginUser;
    }


}
